package com.simpleframe.core.net;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

/**
 * 
 * @author liugl
 *
 */
public class URLBuilder {
	
	private String url;
	private Map<String, String> parameters;
	
	public URLBuilder(String url){
		if(url.indexOf("?")!=-1 || url.indexOf("&")!=-1){
			throw new IllegalArgumentException("URL 中不能存在 ? 或 & ");
		}
		this.url = url;
	}
	
	public void addParameter(String name, String value){
		if(StringUtils.isEmpty(name)){
			throw new IllegalArgumentException("name 不能为空");
		}
		if(value==null){
			value = "";
		}
		if(name.indexOf("?")!=-1 || name.indexOf("&")!=-1){
			throw new IllegalArgumentException("name 中不能存在 ? 或 &");
		}
		if(value.indexOf("?")!=-1 || value.indexOf("&")!=-1){
			throw new IllegalArgumentException("value 中不能存在 ? 或 &");
		}
		if(parameters==null){
			parameters = new HashMap<String, String>();
		}
		parameters.put(name, value);
	}
	
	public String getURL(){
		if(parameters!=null){
			StringBuffer urlbff = new StringBuffer(url);
			urlbff.append("?");
			for (Object key : parameters.keySet()) {
				urlbff.append(key);
				urlbff.append("=");
				urlbff.append(StringUtils.trim(parameters.get(key)));
				urlbff.append("&");
			}
			urlbff.delete(urlbff.lastIndexOf("&"), urlbff.length());
			return urlbff.toString();
		}
		return "";
	}
	
	public static void main(String[] args) {
		URLBuilder ub = new URLBuilder("http://localhost:8080");
		ub.addParameter("xxx", null);
		ub.addParameter("cc", "bbbb");
		System.out.println(ub.getURL());
	}
}
